package com.we.flink.userlabelplatform.tag;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;

import com.alibaba.fastjson.JSONObject;
import com.we.flink.userlabelplatform.table.TableTxxyOrderResultCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class TagTxxyOrderResultCallback {
    public long uid;
    public Integer last_txxy_trade_time;

    public static Logger LOG = LoggerFactory.getLogger(TagTxxyOrderResultCallback.class);

    public TagTxxyOrderResultCallback() {}

    public TagTxxyOrderResultCallback(long uid, Integer last_txxy_trade_time) {
        this.uid = uid;
        this.last_txxy_trade_time = last_txxy_trade_time;
    }

    public static TagTxxyOrderResultCallback init(long uid) {
        return new TagTxxyOrderResultCallback(uid, 0);
    }

    public static TagTxxyOrderResultCallback coInit(long uid) {
        return new TagTxxyOrderResultCallback(uid, null);
    }

    public static SingleOutputStreamOperator<String> getFlatMapStream(
            StreamTableEnvironment tableEnv, StreamExecutionEnvironment env) {
        Table tableRes = tableEnv.sqlQuery(TableTxxyOrderResultCallback.QUERYSQL);
        DataStream<Tuple2<Boolean, TableTxxyOrderResultCallback>> inputStream =
                tableEnv.toRetractStream(tableRes, TableTxxyOrderResultCallback.class);

        SingleOutputStreamOperator<String> out =
                inputStream
                        .filter(
                                new FilterFunction<
                                        Tuple2<Boolean, TableTxxyOrderResultCallback>>() {
                                    @Override
                                    public boolean filter(
                                            Tuple2<Boolean, TableTxxyOrderResultCallback> value)
                                            throws Exception {
                                        return value.f0;
                                    }
                                })
                        .uid("TagTxxyOrderResCbk-filter")
                        .keyBy(
                                new KeySelector<
                                        Tuple2<Boolean, TableTxxyOrderResultCallback>, Long>() {
                                    @Override
                                    public Long getKey(
                                            Tuple2<Boolean, TableTxxyOrderResultCallback> value)
                                            throws Exception {
                                        return value.f1.getUid();
                                    }
                                })
                        .flatMap(new TxxyOrderResCallbackFlatMapFunction());

        return out;
    }

    private static class TxxyOrderResCallbackFlatMapFunction
            extends RichFlatMapFunction<Tuple2<Boolean, TableTxxyOrderResultCallback>, String> {
        ValueState<TagTxxyOrderResultCallback> txxyOrderResCallbackVState;

        @Override
        public void open(Configuration parameters) throws Exception {
            txxyOrderResCallbackVState =
                    getRuntimeContext()
                            .getState(
                                    new ValueStateDescriptor<TagTxxyOrderResultCallback>(
                                            "TxxyOrderResCallbackVState",
                                            TagTxxyOrderResultCallback.class));
        }

        @Override
        public void flatMap(
                Tuple2<Boolean, TableTxxyOrderResultCallback> value, Collector<String> out)
                throws Exception {
            TagTxxyOrderResultCallback tmpTxxyOrderResCallback = txxyOrderResCallbackVState.value();
            long uid = value.f1.getUid();
            TagTxxyOrderResultCallback curTxxyOrderResCallback =
                    (tmpTxxyOrderResCallback == null
                            ? TagTxxyOrderResultCallback.init(uid)
                            : tmpTxxyOrderResCallback);

            int trade_time_end = (int) (value.f1.getTrade_time_end().getTime() / 1000);
            if (trade_time_end > curTxxyOrderResCallback.getLast_txxy_trade_time()) {
                curTxxyOrderResCallback.last_txxy_trade_time = trade_time_end;
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("uid", uid);
                jsonObject.put(
                        "last_txxy_trade_time", curTxxyOrderResCallback.getLast_txxy_trade_time());
                out.collect(jsonObject.toString());
                txxyOrderResCallbackVState.update(curTxxyOrderResCallback);
            }
        }
    }

    public long getUid() {
        return uid;
    }

    public Integer getLast_txxy_trade_time() {
        return last_txxy_trade_time;
    }

    public TagTxxyOrderResultCallback outputFormat() {
        this.last_txxy_trade_time =
                (this.getLast_txxy_trade_time() == 0 ? null : this.getLast_txxy_trade_time());
        return this;
    }

    @Override
    public String toString() {
        SimpleDateFormat simpleDateFormat =
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);

        return "{"
                + "uid= "
                + uid
                + ", last_txxy_trade_time= "
                + simpleDateFormat.format(new Date(last_txxy_trade_time * 1000L))
                + " seconds: "
                + last_txxy_trade_time
                + '}';
    }
}
